package com.qf.ssm.service.impl;

import com.qf.ssm.cache.RoleCache;
import com.qf.ssm.dto.ResultCode;
import com.qf.ssm.event.RoleCacheEvent;
import com.qf.ssm.exceptions.AddErrorException;
import com.qf.ssm.exceptions.DeleteErrorException;
import com.qf.ssm.exceptions.UpdateErrorException;
import com.qf.ssm.mapper.RoleMapper;
import com.qf.ssm.pojo.CheckStatus;
import com.qf.ssm.pojo.Role;
import com.qf.ssm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    private RoleMapper roleMapper;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private RoleCache roleCache;

    @Autowired
    public RoleCache getRoleCache() {
        return roleCache;
    }

    @Override
    public List<Role> findRoleByUserId(Long uid) {
        return roleMapper.findRoleByUserId(uid);
    }

    @Override
    public void addRole(Role role) {
        boolean isNull = role.isNull(CheckStatus.ADD);
        if(isNull){
            throw  new AddErrorException("数据不完整,请检查数据", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        roleMapper.addRole(role);
        context.publishEvent(new RoleCacheEvent());
    }

    @Override
    public void updateRole(Role role) {
        if (role.isNull(CheckStatus.UPDATE)){
            throw new UpdateErrorException("更新的数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        roleMapper.updateRole(role);
        context.publishEvent(new RoleCacheEvent());
    }

    @Override
    public void deleteRoleByIds(Long[] ids) {
        if(ids==null||ids.length==0){
            throw new DeleteErrorException("删除必须传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }
           roleMapper.deleteRoleByIds(Arrays.asList(ids));
        context.publishEvent(new RoleCacheEvent());


    }
}
